package com.ragdollcat.thirdaicodegenerate.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ragdollcat.thirdaicodegenerate.core.image.CosManager;
import com.ragdollcat.thirdaicodegenerate.exception.ErrorCode;
import com.ragdollcat.thirdaicodegenerate.exception.ThrowUtils;
import com.ragdollcat.thirdaicodegenerate.service.ScreenShotsService;
import com.ragdollcat.thirdaicodegenerate.util.WebScreenUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.UUID;

/**
 * 截图Service
 */
@Service
public class ScreenShotsServiceImpl implements ScreenShotsService {

    @Resource
    private CosManager cosManager;

    /**
     * 将截图并压缩后的文件，上传到对象存储中
     *
     * @return
     */
    @Override
    public String uploadScreenShot(String projectPath) {
        String compressionPath = null;
        try {
            ThrowUtils.throwIf(StrUtil.isEmpty(projectPath), ErrorCode.OPERATION_ERROR, "项目目录为空，请检查！");
            //得到压缩后的图片路径
            compressionPath = WebScreenUtil.doWebScreen(projectPath);
            ThrowUtils.throwIf(StrUtil.isEmpty(compressionPath), ErrorCode.OPERATION_ERROR, "压缩封面图生成失败！请联系管理员查看日志");
            //上传到对象存储中
            //生成对象存储的路径
            final String fileName = UUID.randomUUID().toString().substring(0, 8) + "_compression.png";
            File file = new File(compressionPath);
            //这里要返回访问路径，用于保存到app表中，并且前端页面展示
            return cosManager.uploadFile("/screen-shots/" + System.currentTimeMillis() + "/" + fileName, file);
            //无论成功还是失败，都删除本地的压缩图片
        } finally {
            WebScreenUtil.delOriginFile(compressionPath);
        }
    }


}
